package com.pys.beans;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import org.apache.commons.lang.StringUtils;

import com.pys.common.beans.BaseBean;
import com.pys.pojo.PysTalepOncelik;
import com.pys.service.OncelikService;
import com.pys.utils.FacesUtils;

@ManagedBean
@ViewScoped
public class TalepOncelikBean extends BaseBean implements Serializable {
	private String ad;
	private boolean durum = true;
	private List<PysTalepOncelik> list;
	private PysTalepOncelik selectedOncelik;

	public TalepOncelikBean() {
		refreshList();
	}

	/*
	 * ACTIONS
	 */
	public void refreshList() {
		OncelikService oncelikService = new OncelikService();
		list = oncelikService.getAllList(false);
	}

	public void saveAction() {
		if (StringUtils.isBlank(ad)) {
			FacesUtils.addMessage(FacesMessage.SEVERITY_ERROR,
					"VALIDATION_TALEP_ONCELIK_AD");
			return;
		}

		OncelikService oncelikService = new OncelikService();
		if (selectedOncelik == null) {
			PysTalepOncelik pysOncelik = new PysTalepOncelik();
			pysOncelik.setAd(ad);
			pysOncelik.setDurum(durum);
			pysOncelik.setOlusturmaTarih(new Date());
			pysOncelik.setPysKullanici(FacesUtils.getUserSession()
					.getCurrentUser());
			oncelikService.save(pysOncelik);
		} else {
			selectedOncelik.setAd(ad);
			selectedOncelik.setDurum(durum);
			selectedOncelik.setGuncellemeTarih(new Date());
			selectedOncelik.setPysKullanici(FacesUtils.getUserSession()
					.getCurrentUser());
			oncelikService.update(selectedOncelik);
		}
		refreshList();
		clear();
		FacesUtils.successMessage();
	}

	public void deleteAction() {
		OncelikService oncelikService = new OncelikService();
		selectedOncelik.setDeleted(true);
		oncelikService.update(selectedOncelik);
		refreshList();
		clear();
		FacesUtils.successMessage();
	}

	public void updateAction() {
		ad = selectedOncelik.getAd();
		durum = selectedOncelik.isDurum();
	}

	public void clear() {
		selectedOncelik = null;
		ad = null;
		durum = true;
	}

	/*
	 * GETTER-SETTER
	 */

	public String getAd() {
		return ad;
	}

	public void setAd(String ad) {
		this.ad = ad;
	}

	public List<PysTalepOncelik> getList() {
		return list;
	}

	public void setList(List<PysTalepOncelik> list) {
		this.list = list;
	}

	public PysTalepOncelik getSelectedOncelik() {
		return selectedOncelik;
	}

	public void setSelectedOncelik(PysTalepOncelik selectedRole) {
		this.selectedOncelik = selectedRole;
	}

	public boolean isDurum() {
		return durum;
	}

	public void setDurum(boolean durum) {
		this.durum = durum;
	}

}
